# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : 单一聚合sum操作.py
# @Author: dongguangwen
# @Date  : 2025-06-14 19:06
from pymongo import MongoClient

# 连接到MongoDB（默认端口27017）
client = MongoClient('mongodb://root:root123@192.168.1.119:27017/')

# 创建数据库和集合
db = client['learning_mongodb']
collection = db['users']


pipeline = [
    {
        "$group": {
            "_id": None,
            "total_age": {"$sum": "$age"}
        }
    }
]

result = list(db.users.aggregate(pipeline))
print(result)
print("总年龄:", result[0]["total_age"])


"""
[{'_id': None, 'total_age': 355}]
总年龄: 355
"""